﻿var markerNames = {
    0: 'LeftEyeInnerLidJunction',
    26: 'LeftEyeOuterLidJunction',
    2: 'LeftEyeIrisCenter',
    3: 'LeftEyeUpperCurveMaxima',
    4: 'LeftEyeLowerCurveMaxima',
    5: 'LeftInnerBrow',
    27: 'LeftOuterBrow',
    7: 'RightEyeInnerLidJunction',
    28: 'RightEyeOuterLidJunction',
    9: 'RightEyeIrisCenter',
    10: 'RightEyeUpperCurveMaxima',
    11: 'RightEyeLowerCurveMaxima',
    12: 'RightInnerBrow',
    29: 'RightOuterBrow',
    30: 'NoseTop',
    31: 'NoseBottom',
    32: 'NoseLeftOuterNostril',
    17: 'NoseLeftInnerNostril',
    33: 'NoseRightOuterNostril',
    19: 'NoseRightInnerNostril',
    34: 'MouthUpperLipTop',
    21: 'MouthUpperLipBottom',
    22: 'MouthLowerLipTop',
    35: 'MouthLowerLipBottom',
    36: 'MouthLeftExtent',
    37: 'MouthRightExtent',
    38: 'JawLineTopLeft',
    39: 'JawLineTopRight',
    40: 'MouthLowerExtent',
    1: 'EyeBoundary1',
    6: 'EyeBoundary2',
    8: 'EyeBoundary3',
    13: 'EyeBoundary4',
    14: 'NoseBoundary1',
    15: 'NoseBoundary2',
    16: 'NoseBoundary3',
    18: 'NoseBoundary4',
    20: 'MouthBoundary1',
    23: 'MouthBoundary2',
    24: 'MouthBoundary3',
    25: 'MouthBoundary4'
}

var featureData = {
    1: {
        Id: 0,
        Layers: [17],
        Markers: {
            'LeftEyeInnerLidJunction': null,
            'LeftEyeOuterLidJunction': null,
            'LeftEyeIrisCenter': null,
            'LeftEyeUpperCurveMaxima': null,
            'LeftEyeLowerCurveMaxima': null,
            'LeftInnerBrow': null,
            'LeftOuterBrow': null,
            'RightEyeInnerLidJunction': null,
            'RightEyeOuterLidJunction': null,
            'RightEyeIrisCenter': null,
            'RightEyeUpperCurveMaxima': null,
            'RightEyeLowerCurveMaxima': null,
            'RightInnerBrow': null,
            'RightOuterBrow': null
        }
    },
    2: {
        Id: 0,
        Layers: [],
        Markers: {
            'NoseTop': null,
            'NoseBottom': null,
            'NoseLeftOuterNostril': null,
            'NoseLeftInnerNostril': null,
            'NoseRightOuterNostril': null,
            'NoseRightInnerNostril': null
        }
    },
    3: {
        Id: 0,
        Layers: [24],
        Markers: {
            'MouthUpperLipTop': null,
            'MouthUpperLipBottom': null,
            'MouthLowerLipTop': null,
            'MouthLowerLipBottom': null,
            'MouthLeftExtent': null,
            'MouthRightExtent': null
        }
    },
    4: {
        Id: 0,
        Layers: [2, 21, 1],
        Markers: {
            'LeftEyeInnerLidJunction' : null,
            'LeftEyeOuterLidJunction' : null,
            'LeftEyeIrisCenter' : null,
            'LeftEyeUpperCurveMaxima' : null,
            'LeftEyeLowerCurveMaxima' : null,
            'LeftInnerBrow' : null,
            'LeftOuterBrow' : null,
            'RightEyeInnerLidJunction' : null,
            'RightEyeOuterLidJunction' : null,
            'RightEyeIrisCenter' : null,
            'RightEyeUpperCurveMaxima' : null,
            'RightEyeLowerCurveMaxima' : null,
            'RightInnerBrow' : null,
            'RightOuterBrow' : null,
            'NoseTop' : null,
            'NoseBottom' : null,
            'NoseLeftOuterNostril' : null,
            'NoseLeftInnerNostril' : null,
            'NoseRightOuterNostril' : null,
            'NoseRightInnerNostril' : null,
            'MouthUpperLipTop' : null,
            'MouthUpperLipBottom' : null,
            'MouthLowerLipTop' : null,
            'MouthLowerLipBottom' : null,
            'MouthLeftExtent' : null,
            'MouthRightExtent' : null
        }
    }
};

var layerData = {
    17: {
        Name: 'EyesColor',
        Color: '52afdd'
    },
    24: {
        Name: 'MouthLipColor',
        Color: 'ff0000'
    },
    2: {
        Name: 'FaceColor',
        Color: 'd7c982'
    },
    21: {
        Name: 'HairShapeAboveColor',
        Color: '5e4923'
    },
    1: {
        Name: 'HairShapeBelowColor',
        Color: '5e4923'
    }
};

var currentFeatureTypeId = 4;
var currentOffset = 0;
var currentMaxCount = 16;
var forwardIsEnabled = true;
var backIsEnabled = true;
var onUpdateFeatures;
var onSetPortrait;
var showMarkers = false;
var postProcessSvg;

function backPage() {
    if (!backIsEnabled) return;
    updateAvailableFeatures(currentFeatureTypeId, currentOffset - currentMaxCount, currentMaxCount);
}

function forwardPage() {
    if (!forwardIsEnabled) return;
    updateAvailableFeatures(currentFeatureTypeId, currentOffset + currentMaxCount, currentMaxCount);
}

function updateSelectedFeatureTab(element) {
    $("div.FeatureSelector div").attr("class", "FeatureTab");
    $(element.parentNode).attr("class", "FeatureTabEnabled");
}

function updateAvailableFeatures(featureTypeId, offset, maxCount, element) {
    if (element != null) {
        updateSelectedFeatureTab(element);
    }

    if (onUpdateFeatures != null) onUpdateFeatures(featureTypeId);

    currentFeatureTypeId = featureTypeId;
    currentOffset = offset;
    currentMaxCount = maxCount;

    $.ajax({
        url: "../Portrait/GetFeatureIds?featureTypeId=" + featureTypeId + "&offset=" + offset + "&maxCount=" + maxCount,
        success: function (data) {
            $("span.SelectableImage").each(function (index, value) {
                value.innerHTML = "<svg />";
                value.onclick = function () { };
            });
            $("span.SelectableImage")
            .each(function (index, value) {
                if (data.FeatureIds.length <= index) return;
                var faceIdentifier = data.FeatureIds[index];

                updateSvgInElement(faceIdentifier, featureTypeId, value, 120);

                value.onclick = function () { updatePortraitFeature(featureTypeId, faceIdentifier); };
            });
            enablePageForward(forwardIsEnabled = data.Offset + data.MaxCount < data.TotalFeatures);
            enablePageBack(backIsEnabled = data.Offset > 0);
        }
    });
}

function updateSvgInElement(faceIdentifier, featureTypeId, element, size, onCompleteLoad) {
    $.ajax({ url: "../FaceDisplay/GetSvg?faceIdentifier=" + faceIdentifier + "&showMarkers=" + showMarkers,
        dataType: "xml",
        success: function (faceData) {
            var ratio = Number(window.innerWidth) / 1920.0;
            $(faceData).find("svg").attr("height", size * ratio);
            $(faceData).find("svg").attr("width", size * ratio);
            for (var j = 1; j <= 4; j++) {
                if (featureTypeId != null && featureTypeId != j) continue;

                for (var i = 0; i < featureData[j].Layers.length; i++) {
                    var layerId = featureData[j].Layers[i];
                    var layerType = layerData[layerId].Name;
                    var color = layerData[layerId].Color;
                    $(faceData)
                        .find("path[layer_type='" + layerType + "']")
                        .each(function (index, value) {
                            $(value).attr('style', 'fill:#' + color + ';fill-opacity:1;');
                        });
                }
            }

            var serializer = new XMLSerializer();
            $(element).html(serializer.serializeToString(faceData));

            if (postProcessSvg != null) postProcessSvg();
            if (onCompleteLoad != null) onCompleteLoad();
        },
        error: function (t, errorText) {
        }
    });
}

function enablePageForward(enabled) {
    if (!enabled)
        $(".ForwardNavigation").attr("class", "ForwardNavigationDisabled");
    else
        $(".ForwardNavigationDisabled").attr("class", "ForwardNavigation");
}

function enablePageBack(enabled) {
    if (!enabled)
        $(".BackNavigation").attr("class", "BackNavigationDisabled");
    else
        $(".BackNavigationDisabled").attr("class", "BackNavigation");
}

function updatePortraitFeature(featureTypeId, featureId) {
    if (featureTypeId == 1) featureData[1].Id = featureId;
    else if (featureTypeId == 2) featureData[2].Id = featureId;
    else if (featureTypeId == 3) featureData[3].Id = featureId;
    else featureData[4].Id = featureId;

    var faceIdentifier = featureData[4].Id + "|" + layerData[2].Color + "|" + layerData[21].Color
        + "_" + featureData[1].Id + "|" + layerData[17].Color
        + "_" + featureData[2].Id
        + "_" + featureData[3].Id + "|" + layerData[24].Color;

    updateSvgInElement(faceIdentifier, null, $(".FullSizeImage"), 500, onSetPortrait);
}

function hilight(element, active) {
    var hilightElement = $(element.parentNode).children().first();
    if (active)
        hilightElement.attr("style", "fill:#ffffff;fill-opacity:1;");
    else
        hilightElement.attr("style", "fill:#808080;fill-opacity:1;");
}

$(function () {
    updateAvailableFeatures(currentFeatureTypeId, currentOffset, currentMaxCount);
    $('#frm').submit(function () {
        $(this).ajaxSubmit({
            success: function () { apprise('Saved successfully.'); },
            error: function (error, status, errorThrown) { apprise(errorThrown); }
        }
        );
        return false;
    });
});